<!-- 中医体质辨识页面  wk-2022-12-27 -->
<script setup lang='ts' name="ConstitutionIdentify">
import {ref, reactive, watch, onActivated} from 'vue'
import { ElMessage, ElMessageBox} from 'element-plus'
import {HeaderData} from '@/components/dTable/dTable'
import {SearchFromItem, SearchFromJustify} from '@/components/dTable/dHeader'
import {IconConfig} from '@/api/config'
import {saveIdentificationInfor, SaveInfor, SearchIdentificationData, BaseQuestions, getcheckupRegisterList, getReportDoc} from '@/api/medicalExaminerDesk/constitutionIdentify'
import dTablePromote from '@/components/dTable/dTablePromote.vue'
import {getYearMonthDayStr} from '@/util/common'
import {useRoute} from 'vue-router'
import dIcon from '@/components/dIcon.vue'
import useStore from '@/store/user'
import addGuide from './addHealthGuide.vue'
import codetype from './codeType.vue'
import {showCLodopTips, loadCLodop, checkPrint, printPdf} from '@/util/cLodop'
import {getPdfBase64} from '@/util/pdf'
const {store} = useStore.setup()

const route = useRoute()
const baseQuestions:Array<BaseQuestions> = [{
  title:'1.您精力充沛吗？（指精神头足，乐于做事）',
  option:5
}, {
  title:'2.您容易疲乏吗？（指体力如何，是否稍微活动一下或做一点家务劳动就感到累）',
  option:1
}, {
  title:'3.您容易气短，呼吸短促，接不上气吗？',
  option:1
}, {
  title:'4.您说话声音低弱无力吗？（指说话没有力气）',
  option:1
}, {
  title:'5.您感到闷闷不乐、情绪低沉吗？（指心情不愉快，情绪低落）',
  option:1
}, {
  title:'6.您容易精神紧张、焦虑不安吗？（指遇事是否心情紧张）',
  option:1
}, {
  title:'7.您因为生活状态改变而感到孤独、失落吗？',
  option:1
}, {
  title:'8.您容易感到害怕或受到惊吓吗？',
  option:1
}, {
  title:'9.您感到身体超重不轻松吗？(感觉身体沉重)[BMI指数=体重（kg）/身高²（㎡）]',
  helpTitle:'1.(BMI<24)  2.(24≤BMI<25)   3.(25≤BMI<26)   4.(26≤BMI<28)   5.(BMI≥28)',
  option:1
}, {
  title:'10.您眼睛干涩吗？',
  option:1
}, {
  title:'11.您手脚发凉吗？（不包含周围温度低或穿的少导致的手脚发冷）',
  option:1
}, {
  title:'12.您胃脘部、背部或腰膝部怕冷吗？（指上腹部、背部、腰部或膝关节等，有一处或多处怕冷）',
  option:1
}, {
  title:'13.您比一般人耐受不了寒冷吗？（指比别人容易害怕冬天或是夏天的冷空调、电扇等）',
  option:1
}, {
  title:'14.您容易患感冒吗？（指每年感冒的次数）',
  helpTitle:'1.(一年<2次)  2.(一年感冒2-4次)   3.(一年感冒5-6次)   4.(一年8次以上)  5.(几乎每月都感冒)',
  option:1
}, {
  title:'15.您没有感冒时也会鼻塞、流鼻涕吗？',
  option:1
}, {
  title:'16.您有口黏口腻，或睡眠打鼾吗？',
  option:1
}, {
  title:'17.您容易过敏(对药物、食物、气味、花粉或在季节交替、气候变化时)吗？',
  helpTitle:'1.(从来没有)  2.(一年1、2次)  3.(一年3、4次)  4.(一年5、6次)  5.(每次遇到上述原因都过敏)',
  option:1
}, {
  title:'18.您的皮肤容易起荨麻疹吗？ (包括风团、风疹块、风疙瘩)',
  option:1
}, {
  title:'19.您的皮肤在不知不觉中会出现青紫瘀斑、皮下出血吗？（指皮肤在没有外伤的情况下出现青一块紫一块的情况）',
  option:1
}, {
  title:'20.您的皮肤一抓就红，并出现抓痕吗？（指被指甲或钝物划过后皮肤的反应）',
  option:1
}, {
  title:'21.您皮肤或口唇干吗？',
  option:1
}, {
  title:'22.您有肢体麻或固定部位疼痛的感觉吗？',
  option:1
}, {
  title:'23.您面部或鼻部有油腻感或者油亮发光吗？（指脸上或鼻子）',
  option:1
}, {
  title:'24.您面色或目眶晦黯，或出现褐色斑块/斑点吗？',
  option:1
}, {
  title:'25.您有皮肤湿疹、疮疖吗？',
  option:1
}, {
  title:'26.您感到口干咽燥、总想喝水吗？',
  option:1
}, {
  title:'27.您感到口苦或嘴里有异味吗？（指口苦或口臭）',
  option:1
}, {
  title:'28.您腹部肥大吗？（指腹部脂肪肥厚）',
  helpTitle:'1.(腹围<80cm,相当于2.4尺)  2.(腹围80-85cm,相当于2.4-2.55尺)  3.(腹围86-90cm,相当于2.56-2.7尺) 4.(腹围91-105cm,相当于2.71-3.15尺)    5.(腹围>105cm,相当于3.15尺) ',
  option:5
}, {
  title:'29.您吃(喝)凉的东西会感到不舒服或者怕吃(喝)凉的东西吗？（指不喜欢吃凉的食物，或吃了凉的食物后会不舒服）',
  option:1
}, {
  title:'30.您有大便黏滞不爽、解不尽的感觉吗？(大便容易粘在马桶上)',
  option:1
}, {
  title:'31.您容易大便干燥吗？',
  option:1
}, {
  title:'32.您舌苔厚腻或有舌苔厚厚的感觉吗？（如果自我感觉不清楚可由调查员观察后填写）',
  option:1
}, {
  title:'33.您舌下静脉瘀紫或增粗吗？（可由调查员辅助观察后填写）',
  option:1
}]
const queryRow = ref()
// 分型结果
const result = ref('')
//当前页面 表格数据 定义
const tableData = ref<Array<BaseQuestions>>(baseQuestions)
// 分数类型基本数据
const baseBot = [{
  constitution:'体质辨识',
  qiDeficiency:{code:0, type:0, label:'气虚质'},
  yangDeficiency:{code:0, type:0, label:'阳虚质'},
  yinDeficiency:{code:0, type:0, label:'阴虚质'},
  phlegmDeficiency:{code:0, type:0, label:'痰湿质'},
  dampHeat:{code:0, type:0, label:'湿热质'},
  bloodStasis:{code:0, type:0, label:'血瘀质'},
  qiStagnation:{code:0, type:0, label:'气郁质'},
  specialQuality:{code:0, type:0, label:'特禀质'},
  peacefulQuality:{code:0, type:0, label:'平和质'}
}]
const guideDeatil = ref<Array<string>>([])
// 分数类型基本数据实例
const tableDataBot = ref(JSON.parse(JSON.stringify(baseBot)))
// 头部信息
const topInfoList = ref([['体检号'], ['姓名'], ['性别'], ['年龄'], ['体质辨识'], ['居住地址'], ['既往史']])

//显示加载状态
const showLoading = ref(false)
//是否展示
const loading = ref(false)

const SaveInforTemp = {checkupRegisterId:'', evaluationTime:'', constitution:'', result:'', questions:'', guideValue:'', dutyDoctorId:'', dutyDoctorName:'', checkupStatus:'', synchStatus:'', guideWriteValue:''}
// 保存的数据
const saveInfo = ref<SaveInfor>(JSON.parse(JSON.stringify(SaveInforTemp)))
//表格头部数据定义
const tableHeaderData = ref<Array<HeaderData>>([
  {prop:'title', label:'题目信息', columnType:'slot', align:'left', 'min-width':'100'},
  {prop:'option', label:'选项', columnType:'slot', align:'left', 'width':'480', fixed:'right'}
])

const tableHeaderDataBot = ref<Array<HeaderData>>([
  {prop:'constitution', label:'体质类型', columnType:'text', align:'center', 'min-width':'100', columnStyle:{height:'200px'}},
  {prop:'qiDeficiency', label:'气虚质', columnType:'slot', align:'center', 'min-width':'100'},
  {prop:'yangDeficiency', label:'阳虚质', columnType:'slot', align:'center', 'min-width':'100'},
  {prop:'yinDeficiency', label:'阴虚质', columnType:'slot', align:'center', 'min-width':'100'},
  {prop:'phlegmDeficiency', label:'痰湿质', columnType:'slot', align:'center', 'min-width':'100'},
  {prop:'dampHeat', label:'湿热质', columnType:'slot', align:'center', 'min-width':'100'},
  {prop:'bloodStasis', label:'血瘀质', columnType:'slot', align:'center', 'min-width':'100'},
  {prop:'qiStagnation', label:'气郁质', columnType:'slot', align:'center', 'min-width':'100'},
  {prop:'specialQuality', label:'特禀质', columnType:'slot', align:'center', 'min-width':'100'},
  {prop:'peacefulQuality', label:'平和质', columnType:'slot', align:'center', 'min-width':'100'}
])

//保存后自动填写数据
const searchFromItems = ref<Array<SearchFromItem>>([
  {label:'医生：',  prop:'dutyDoctorName', type:'input', disabled:true, style:{marginLeft:'-30px'}},
  {label:'评估日期：',  prop:'evaluationTime', type:'input', disabled:true},
  {label:'分型结果：',  prop:'result', type:'input', disabled:true, style:{width:'586px'}},
  {label:'',  prop:'button', type:'slot', slotName:'button'}
])

// 保存后自动填写数据
const searchFromData = reactive<SearchIdentificationData>({dutyDoctorName:null, evaluationTime:null, result:'', dutyDoctorId:null})

//表单靠左还是靠右
const searchFromJustify = ref<SearchFromJustify>('flexStart')
const printData = ref<any>()
const registerStatus = ref(0)
//数据拼接字段事件
const setTableData = (rows:any) => {
  saveInfo.value.checkupRegisterId = rows.id
  const tableNewData = JSON.parse(JSON.stringify(baseQuestions))
  getcheckupRegisterList(rows.id).then((res) => {
    const {data} = res.data
    if (data)saveInfo.value = {...data}
    topInfoList.value = [['体检号', rows.checkupNo], ['姓名', rows.personName], ['性别', rows.gender], ['年龄', rows.age], ['体质辨识', saveInfo.value.result], ['居住地址', rows.address], ['既往史', rows.pastHistory]]
    printData.value = JSON.parse(JSON.stringify({...data, ...rows}))
    if (saveInfo.value.questions) {
      const options = JSON.parse(saveInfo.value.questions)
      tableNewData.forEach((item, index) => {
        item.option = options[index]
      })
    }
    searchFromData.dutyDoctorId = saveInfo.value.dutyDoctorId
    searchFromData.dutyDoctorName = saveInfo.value.dutyDoctorName
    searchFromData.evaluationTime = saveInfo.value.evaluationTime
    searchFromData.result = saveInfo.value.result
    registerStatus.value = +rows.registerStatus
    if (saveInfo.value.result || +rows.registerStatus > 2)loading.value = true
    guideDeatil.value = saveInfo.value.guideValue ? JSON.parse(saveInfo.value.guideValue) : []
    tableData.value = tableNewData
  })
}

watch(() => tableData.value, (newValue) => {
  //重置分数选项
  for (const k in tableDataBot.value[0]) {
    if (k !== 'constitution') {
      tableDataBot.value[0][k].code = 0
      tableDataBot.value[0][k].type = 0
    }
  }
  result.value = ''
  //是否除平和质全都大于8
  const isEieght = ref(true)
  //是否除平和质全都大于10
  const isTen = ref(true)
  if (newValue) {
    // 计分
    newValue.map((item, index) => {
      switch (index + 1) {
      case 3:
      case 14:
        tableDataBot.value[0].qiDeficiency.code += item.option
        break
      case 2:
      case 4:
        tableDataBot.value[0].qiDeficiency.code += item.option
        tableDataBot.value[0].peacefulQuality.code += item.option ? (6 - item.option) : item.option
        break
      case 11:
      case 12:
      case 29:
        tableDataBot.value[0].yangDeficiency.code += item.option
        break
      case 13:
        tableDataBot.value[0].yangDeficiency.code += item.option
        tableDataBot.value[0].peacefulQuality.code += item.option ? (6 - item.option) : item.option
        break
      case 10:
      case 21:
      case 26:
      case 31:
        tableDataBot.value[0].yinDeficiency.code +=  item.option
        break
      case 9:
      case 16:
      case 28:
      case 32:
        tableDataBot.value[0].phlegmDeficiency.code += item.option
        break
      case 23:
      case 25:
      case 27:
      case 30:
        tableDataBot.value[0].dampHeat.code +=  item.option
        break
      case 19:
      case 22:
      case 24:
      case 33:
        tableDataBot.value[0].bloodStasis.code += item.option
        break
      case 6:
      case 7:
      case 8:
        tableDataBot.value[0].qiStagnation.code += item.option
        break
      case 15:
      case 17:
      case 18:
      case 20:
        tableDataBot.value[0].specialQuality.code += item.option
        break
      case 5:
        tableDataBot.value[0].qiStagnation.code += item.option
        tableDataBot.value[0].peacefulQuality.code += item.option ? (6 - item.option) : item.option
        break
      case 1:
        tableDataBot.value[0].peacefulQuality.code += item.option ? item.option : 0
        break
      }
    })
    // 算型
    for (const k in tableDataBot.value[0]) {
      if (k !== 'peacefulQuality' && k !== 'constitution') {
        if (tableDataBot.value[0][k].code && tableDataBot.value[0][k].code >= 11) {
          tableDataBot.value[0][k].type = 1
          result.value += (result.value ? '、' : '') + tableDataBot.value[0][k].label
        } else if (tableDataBot.value[0][k].code && tableDataBot.value[0][k].code >= 9) {
          tableDataBot.value[0][k].type = 2
          result.value += (result.value ? '、' : '') + tableDataBot.value[0][k].label
        } else {
          tableDataBot.value[0][k].type = 3
        }
        if (tableDataBot.value[0][k].code && tableDataBot.value[0][k].code > 8) isEieght.value = false
        if (tableDataBot.value[0][k].code && tableDataBot.value[0][k].code > 10) isTen.value = false
      }
    }
    if (tableDataBot.value[0].peacefulQuality.code && tableDataBot.value[0].peacefulQuality.code >= 17 && isEieght.value) {
      tableDataBot.value[0].peacefulQuality.type = 1
      result.value += (result.value ? '、' : '') + tableDataBot.value[0].peacefulQuality.label
    } else if (tableDataBot.value[0].peacefulQuality.code && tableDataBot.value[0].peacefulQuality.code >= 17 && isTen.value) {
      tableDataBot.value[0].peacefulQuality.type = 2
      result.value += (result.value ? '、' : '') + tableDataBot.value[0].peacefulQuality.label
    } else {
      tableDataBot.value[0].peacefulQuality.type = 3
    }
  }
}, {deep:true, immediate:true})
//显示弹窗
const showDialog = ref(false)

// 保存信息
const onSave = () => {
  const noFinishList = tableData.value.filter(item => !item.option)
  if (noFinishList.length) {
    ElMessage({
      type: 'warning',
      message: '第' + (tableData.value.indexOf(noFinishList[0]) + 1) + '题' + '未作答'
    })
    return
  } else {
    searchFromData.dutyDoctorId = searchFromData.dutyDoctorId ? searchFromData.dutyDoctorId : store.userInfor?.id + ''
    searchFromData.dutyDoctorName = searchFromData.dutyDoctorName ? searchFromData.dutyDoctorName : store.userInfor?.userName + ''
    searchFromData.evaluationTime = getYearMonthDayStr(Date.now())
    searchFromData.result = result.value
    if (saveInfo.value) {
      const options:Array<number> = []
      tableData.value.map((item) => {
        options.push(item.option)
      })
      saveInfo.value.questions = JSON.stringify(options)
      saveInfo.value = {...saveInfo.value, ...searchFromData}
      loading.value = true
      saveIdentificationInfor(saveInfo.value).then((res) => {
        const {data} = res.data
        saveInfo.value.id = data.id
        ElMessageBox.confirm(
          `分型结果：${searchFromData.result}，是否需要进行健教指导`,
          '提示',
          {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          return showDialog.value = true
        })
      }).catch((error) => {
        console.warn(error)
      })
    }
  }
}

// 图标 打印&健教指导
const printIcon:IconConfig = {icon:'common-print', type:'custom', size:24}
const healthGuide:IconConfig = {icon:'common-health-guide', type:'custom', size:24}

// 点击变更题目信息
const onRowClick = (row) => {
  tableHeaderData.value[0].label = `题目信息 (${tableData.value.indexOf(row) + 1}/33)`
}

//关闭窗口事件
const onClose = () => {
  showDialog.value = false
  setTableData(queryRow.value)
}

async function printHealthPdf() {
  if (!showCLodopTips() || !checkPrint('pdf')) return
  const guideShow = printData.value.constitution ? JSON.parse(printData.value.constitution) : []
  //判断当前存储版本
  printData.value.guideDataList = guideShow.length ? guideShow[0].version === '1.0.0' ? guideShow : [] : []
  printData.value.printDate = getYearMonthDayStr(Date.now())
  printData.value.orgName = store.userOrgInfor?.orgName
  printData.value.tcmConstitutionIdentificationVO = {
    constitution:printData.value.constitution,
    result:printData.value.result,
    guideWriteValue:printData.value.guideWriteValue,
    dutyDoctorName:printData.value.dutyDoctorName
  }
  const base64 = await getPdfBase64(getReportDoc(printData.value), true)
  printPdf('pdf', 'preview', base64)
}

// 接收路由参数初始化数据
onActivated(() => {
  loadCLodop()
  const str = route.query ? route.query : {}
  if (!route.query.id) return
  saveInfo.value = JSON.parse(JSON.stringify(SaveInforTemp))
  loading.value = false
  queryRow.value = str
  setTableData(str)
})
</script>

<template>
  <div class="d-common-flex d-common-flex-full d-common-flex-col page__wapper">
    <el-scrollbar class="header-scrollbar">
      <ul class="begin-physical-examination-header d-common-flex-row">
        <li v-for="item,index in topInfoList" :key="item[0]" :class="index===0?'infor-number':index<4?'infor-name':'infor-text'">
          {{ item[0] }}：
          <el-tooltip class="infor-item" effect="dark" :content="item[1]" placement="top">
            {{ item[1] }}
          </el-tooltip>
        </li>
      </ul>
    </el-scrollbar>

    <el-scrollbar class="constitution-center" :style="{marginTop:'10px',height:'auto',width:'100%'}">
      <d-table-promote
        class="constitution-table"
        :label-width="90"
        :style="{minHeight:'550px'}"
        :show-loading="showLoading"
        :oper-buttons="[]"
        :table-data="tableData"
        :table-header-data="tableHeaderData"
        :search-form-data="searchFromData"
        :search-form-items="searchFromItems"
        :search-from-justify="searchFromJustify"
        :search-buttons="[]"
        @row-click="onRowClick"
      >
        <template #button>
          <div v-if="loading">
            <el-button v-blur type="primary" :force-show-button="true" @click="printHealthPdf()">
              <d-icon v-if="printIcon" :icon-config="printIcon" />
              打印
            </el-button>
            <el-button v-blur type="primary" :force-show-button="true" @click="showDialog=true">
              <d-icon v-if="healthGuide" :icon-config="healthGuide" />
              健教指导
            </el-button>
          </div>
        </template>
        <template #title="scope">
          <div>
            {{ scope.row.title }}
          </div>
          <div>
            {{ scope.row.helpTitle?scope.row.helpTitle:'' }}
          </div>
        </template>
        <template #option="scope">
          <el-radio-group v-model="scope.row.option" :disabled="loading" class="d-common-flex-row">
            <el-radio :label="1" size="large">
              1没有
            </el-radio>
            <el-radio :label="2" size="large">
              2很少
            </el-radio>
            <el-radio :label="3" size="large">
              3有时
            </el-radio>
            <el-radio :label="4" size="large">
              4经常
            </el-radio>
            <el-radio :label="5" size="large">
              5总是
            </el-radio>
          </el-radio-group>
        </template>
      </d-table-promote>
      <d-table-promote
        class="bot"
        :style="{height:'250px'}"
        :table-row-height="200"
        :label-width="70"
        :show-loading="showLoading"
        :oper-buttons="[]"
        :table-data="tableDataBot"
        :table-header-data="tableHeaderDataBot"
        :search-buttons="[]"
      >
        <template #qiDeficiency="scope">
          <codetype :row="scope.row" :col="scope.item" />
        </template>
        <template #yangDeficiency="scope">
          <codetype :row="scope.row" :col="scope.item" />
        </template>
        <template #phlegmDeficiency="scope">
          <codetype :row="scope.row" :col="scope.item" />
        </template>
        <template #dampHeat="scope">
          <codetype :row="scope.row" :col="scope.item" />
        </template>
        <template #bloodStasis="scope">
          <codetype :row="scope.row" :col="scope.item" />
        </template>
        <template #qiStagnation="scope">
          <codetype :row="scope.row" :col="scope.item" />
        </template>
        <template #specialQuality="scope">
          <codetype :row="scope.row" :col="scope.item" />
        </template>
        <template #peacefulQuality="scope">
          <codetype :row="scope.row" :col="scope.item" />
        </template>
        <template #yinDeficiency="scope">
          <codetype :row="scope.row" :col="scope.item" />
        </template>
      </d-table-promote>
    </el-scrollbar>
    <div class="guide-save-footer d-common-flex-center">
      <el-button v-if="!loading" v-blur type="primary" :style="{width:'148px'}" @click="onSave">
        保存
      </el-button>
    </div>
  </div>
  <add-guide
    v-if="showDialog"
    :show-dialog="showDialog"
    :guide-deatil="guideDeatil"
    :result="searchFromData.result"
    :save-info="saveInfo"
    :register="registerStatus"
    @close="onClose"
  />
</template>

<style lang="less" scoped>
.page__wapper {
  background-color: var(--d-color-grey-2);
  padding: var(--d-margin-level-2) var(--d-margin-level-2) 0 var(--d-margin-level-2);
}
.begin-physical-examination-header {
  justify-content: flex-start;
  align-items: center;
  list-style: none;
  height: 56px;
  min-width: fit-content;
  padding: 18px 23px;
  margin-bottom: 10px;
  box-shadow: 0px 0px 3px 1px rgba(0, 0, 0, 0.1);
  background: var(--d-color-white);
  color: var(--d-font-color-text);
  white-space: nowrap;
  li {
    margin-right: 40px;
    display: flex;
    align-items: center;
    span {
      display: inline-block;
      max-width: 150px;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    &.infor-text {
      span {
        max-width: 120px;
      }
    }
  }
}
.header-scrollbar {
  height: 56px;
}

.constitution-center{
  background: var(--d-color-white);
}
.constitution-table{
  :deep(.d-table-from-con){
    margin-top: 10px;
    margin-bottom: 10px;
  }
}
</style>
<style scoped>
.guide-save-footer{
  height: 60px;
  background-color: #fff;
}
</style>
<style lang="less">
  .bot{
    .d-table-header__wapper{
      height: 0px;
    }
    .d-footer__wapper{
      --d-footer-lineheight:0px;
      height: 0px;
      line-height: 0px;
    }
    .el-radio-group{
    justify-content: center;
    display: table;
    }
    .el-radio{
      align-items:center;
      display: flex;
    }
  }
</style>